﻿using HookupAppForm.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HookupAppForm
{
    public partial class FormSelTakeOff : Form
    {
        private readonly string apiSubmain = "api/services/app/HKP_Submain/";
        private readonly string apiTakeOff = "api/services/app/HKP_TakeOff/";
        private readonly string apiHDC = "api/services/app/HKP_HDC/";
        private readonly string apiSysReq = "api/services/app/HKP_ToolSysReq/";

        private APIClient Client;
        private HKP_BlockDto Block { get; set; }
        private HKP_ToolDto Tool { get; set; }
        public FormSelTakeOff(APIClient _client, HKP_BlockDto _block, HKP_ToolDto _tool)
        {
            InitializeComponent();
            Client = _client;
            Block = _block;
            Tool = _tool;
        }

        private void FormSelTakeOff_Load(object sender, EventArgs e)
        {
            string url = string.Format(apiTakeOff + "GetList?blockId={0}", Block.Id);
            var result = Client.Get(url);
            ItemsDto<HKP_TakeoffDtoChk> res = JsonConvert.DeserializeObject<ItemsDto<HKP_TakeoffDtoChk>>(result);
            if (res.result == null)
            {
                Utils.SysMsg("没有接点可用", MessageBoxIcon.Warning);
                this.Close();
            }
            var lists = res.result.items.ToList();
            lists = lists.Where(o => !o.Used && o.Enabled).ToList();
            if (lists.Count <= 0)
            {
                Utils.SysMsg("没有剩余接点可用", MessageBoxIcon.Warning);
                this.Close();
            }

            var sysReqArr = GetToolSysReq(Tool.ToolId);
            foreach (var item in lists)
            {
                HKP_SubmainDto submainDto = GetObject<HKP_SubmainDto>(item.SubmainId.ToString(), apiSubmain, "GetById");
                item.Submain = submainDto;
            }
            List<HKP_TakeoffDtoChk> newList = new();
            bool ischk = true, ischk2 = true, ischk3 = true;
            foreach (HKP_ToolSysReqDto sys in sysReqArr)
            {
                ischk = true; ischk2 = true; ischk3 = true;
                string reason = string.Empty;
                var obj = lists.Where(o => o.Submain.SysNo == sys.SysNo).FirstOrDefault();
                if (obj != null)
                {
                    //接点外径
                    double waijin = Utils.FtToInMM(obj.OutSize, obj.OutSizeUnit);

                    //机台接口外径
                    double waijinTool = Utils.FtToInMM(sys.OutSize, sys.OutSizeUnit);

                    if (waijinTool > waijin)
                    {
                        reason += "外径尺寸不相符；";
                        ischk = false;
                    }

                    if (obj.OutType != sys.OutType)
                    {
                        reason += "接口类型不相符；";
                        ischk2 = false;
                    }
                    if (Utils.ConvertFlow(obj.FlowPeakOperation, obj.FlowUnit) < Utils.ConvertFlow(sys.FlowPeak, sys.FlowUnit))
                    {
                        reason += "流量大小不能超过接口操作流量峰值；";
                        ischk3 = false;
                    }
                    obj.OutSizeTool = sys.OutSize + sys.OutSizeUnit;
                    obj.FlowPeakTool = sys.FlowPeak;
                    obj.FlowPeakToolUnit = sys.FlowUnit;
                    obj.OutTypeTool = sys.OutType;
                    obj.Reason = reason;
                    obj.Checked = ischk && ischk2 && ischk3;
                    obj.SysNo = sys.SysNo;
                    obj.OutSize = obj.OutSize + obj.OutSizeUnit;
                    obj.ToolSysReqId = sys.Id;
                    obj.Distence = Math.Round(Utils.GetDistance(Convert.ToInt32(obj.X), Convert.ToInt32(obj.Y), Convert.ToInt32(Tool.X), Convert.ToInt32(Tool.Y))/100, 2);
                    newList.Add(obj);
                    lists.Remove(obj);
                }
                else
                {
                    HKP_TakeoffDtoChk obj2 = new();
                    obj2.OutSizeTool = sys.OutSize;
                    obj2.FlowPeakTool = sys.FlowPeak;
                    obj2.OutTypeTool = sys.OutType;
                    obj2.Reason = "暂无接点可用";
                    obj2.SysNo = sys.SysNo;
                    newList.Add(obj2);
                }
            }

            dataGridViewM.DataSource = newList;
            FromSetting[] fromSettings = new FromSetting[30];
            fromSettings[0] = new FromSetting { FieldDisplay = "派点", FieldDisplayIndex = 0, FieldWidth = 50, IsReadOnly = true };
            fromSettings[20] = new FromSetting { FieldDisplay = "系统", FieldDisplayIndex = 1, FieldWidth = 60 };
            fromSettings[2] = new FromSetting { FieldDisplay = "接点编号", FieldDisplayIndex = 2 };
            fromSettings[3] = new FromSetting { FieldDisplay = "接点名称", FieldDisplayIndex = 3 };
            fromSettings[5] = new FromSetting { FieldDisplay = "启用", FieldDisplayIndex = 4, FieldWidth = 50 };
            fromSettings[6] = new FromSetting { FieldDisplay = "已派点", FieldDisplayIndex = 5, FieldWidth = 60 };            
            fromSettings[9] = new FromSetting { FieldDisplay = "管径", FieldDisplayIndex = 6 };
            fromSettings[10] = new FromSetting { FieldDisplay = "接点类型", FieldDisplayIndex = 7 };
            fromSettings[13] = new FromSetting { FieldDisplay = "流量", FieldDisplayIndex = 8 };
            fromSettings[16] = new FromSetting { FieldDisplay = "单位", FieldDisplayIndex = 9 };
            fromSettings[17] = new FromSetting { FieldDisplay = "机台管径", FieldDisplayIndex = 10, FieldWidth = 110 };
            fromSettings[18] = new FromSetting { FieldDisplay = "机台接口类型", FieldDisplayIndex = 11, FieldWidth = 110 };
            fromSettings[19] = new FromSetting { FieldDisplay = "机台流量", FieldDisplayIndex = 12 };
            fromSettings[22] = new FromSetting { FieldDisplay = "流量单位", FieldDisplayIndex = 18 };
            fromSettings[11] = new FromSetting { FieldDisplay = "原因", FieldDisplayIndex = 19, FieldWidth = 300, ForeColor = Color.Red };
            fromSettings[28] = new FromSetting { FieldDisplay = "距离(m)", FieldDisplayIndex = 17, ForeColor = Color.OrangeRed };
            Utils.SetHeader(dataGridViewM, fromSettings);

            labelInfo.Text = "楼层：" + Block.Building + "-" + Block.Floor + "，区块：" + Block.BlockName + "，机台编号：" + Tool.ToolId;
        }
        private HKP_ToolSysReqDto[] GetToolSysReq(string toolId)
        {
            string url = string.Format(apiSysReq + "GetList?toolId={0}", toolId);
            var result = Client.Get(url);
            ItemsDto<HKP_ToolSysReqDto> dto = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolSysReqDto>>(result);
            return dto.result.items;
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            var takeoffDtos = dataGridViewM.DataSource as List<HKP_TakeoffDtoChk>;
            takeoffDtos = takeoffDtos.Where(o => o.Checked).ToList();
            foreach (HKP_TakeoffDtoChk item in takeoffDtos)
            {
                if (item.Submain != null)
                    CreateHDC(item, Tool, Block, item.Submain,item.ToolSysReqId);
            }
        }
        private void CreateHDC(HKP_TakeoffDtoChk takeoff, HKP_ToolDto tool, HKP_BlockDto block, HKP_SubmainDto submain, Guid toolSysReqId)
        {
            string act = "Create";
            CreateHKP_HDCDto dto = new()
            {
                ToolId = Guid.Parse(tool.Id),
                Bay = block.BlockName,
                Building = block.Building,
                FabArea = block.BlockName,
                Floor = block.Floor,
                SubmainNo = submain.SubmainNo,
                SysNo = submain.SysNo,
                TakeoffNo = takeoff.TakeoffNo,
                ToolSysReqId = toolSysReqId
            };
            string jsons = JsonConvert.SerializeObject(dto);
            string result = Client.Post(apiHDC + act, jsons);
            if (Utils.ExceptionHandler(result) == null)
            {
                UsedTakeOff(takeoff);
                this.Close();
            }
        }

        private void UsedTakeOff(HKP_TakeoffDtoChk Item)
        {
            if (Item != null)
            {
                HKP_TakeoffDto dto = GetObject<HKP_TakeoffDto>(Item.Id.ToString(), apiTakeOff);
                dto.Used = true;
                string jsons = JsonConvert.SerializeObject(dto);
                Client.Put(apiTakeOff + "Update", jsons);
            }
        }
        private T GetObject<T>(string id,string api, string act = "Get")
        {
            string result = Client.Get(api + act + "?Id=" + id.ToString());
            var resp = Utils.SuccessHandler(result);
            return JsonConvert.DeserializeObject<T>(resp.ToString());
        }
    }
}
